﻿using Core.Common;
using Core.HandleMsg;
using Core.UI;
using CQSDK;
using PuppeteerSharp;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Tool;
using Tool.Web.HttpHelper;
using Tool.Windows.Win32;
using static Core.Common.Global;

namespace Core
{
	public static class Main
	{
		[DllImport("data\\app\\com.acgdmzy.acg\\app.dll", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi)]
		private static extern int _eventGroupMsg(int subType, int msgId, long fromGroup, long fromQQ, string fromAnonymous, string msg, int font);

		public static DateTime startTime = new DateTime(2020, 10, 1);
		public static Dictionary<int, string> MsgDic = new Dictionary<int, string>();

		/// <summary>
		/// 多线程异常
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
		{
			Exception ex;
			if (e.ExceptionObject is AggregateException exception) ex = exception.InnerExceptions[0];
			else ex = e.ExceptionObject as Exception;
			if (Master != 0)
			{
				CQ.SendPrivateMessage(Master, "报告主人，少看点二次元吧发生了异常：\r\n" + ex.Message + "\r\n您可以向我发送重载酷q或重启酷q来重新启动酷q(仅对挂了一个酷q的电脑有效)");
			}
			CQ.SetFatal(string.Format("异常类型：{0}\r\n异常消息：{1}\r\n异常方法：{2}\r\n异常堆栈：{3}\r\n异常命令：{4}", ex.GetType().ToString(), ex.Message, ex.TargetSite, ex.StackTrace, MsgDic[Thread.CurrentThread.ManagedThreadId]));
		}

		public static int Initialize(int AuthCode)
		{
			CQ = new CQAPP { AuthCode = AuthCode };
			AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;////多线程异常
			LogHelp.BoilerEventLog += CQ.AddLogDEBUG;
			return 0;
		}

		//Type=1001 酷Q启动
		public static int AppStartup()
		{
			return 0;
		}

		//Type=1002 酷Q退出
		public static int AppExit()
		{
			return 0;
		}

		//Type=1003 应用已被启用
		public static int AppEnable()
		{
			CQ.应用已启用 = true;
			AppDir = CQ.GetAppFolder();                          //不需要存储应用目录请注释此句

			TweetConfig.Authorization = "Bearer AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA";
			TweetConfig.Path = "-xfUfZsnR_zqjFd-IfrN5A";
			new HttpNet();
			ImagePath = AppDomain.CurrentDomain.BaseDirectory + "data\\image\\少看点二次元\\";
			if (!Directory.Exists(ImagePath)) Directory.CreateDirectory(ImagePath);
			var old = AppDomain.CurrentDomain.BaseDirectory + "data\\image\\二次元动漫\\";
			if (!Directory.Exists(old)) Directory.CreateDirectory(old);
			Global.Init();
			if (Win32Help.IniReadValue(AppDir + "通用设置.ini", "设置", "重启", "0", 255) == "1")
			{
				CQ.SendPrivateMessage(Master, "少看点二次元提醒您,插件已经成功启动\r\n当前插件版本：" + Global.Version);
				Win32Help.IniWriteValue(AppDir + "通用设置.ini", "设置", "重启", "0");
			}
			return 0;
		}

		//Type=1004 应用将被停用
		public static int AppDisable()
		{
			CQ.应用已启用 = false;
			WebSocketClient.Client.Close();
			foreach (var item in hashTable.Values)
			{
				if (item is Tool.Common.Monitor monitor)
				{
					monitor.Close();
				}
			}
			return 0;
		}

		//Type=2 群消息
		public static int GroupMessage(int subType, int msgId, long fromGroup, long fromQQ, string fromAnonymous, string msg, int font)
		{
			MsgDic[Thread.CurrentThread.ManagedThreadId] = msg;
			if (DateTime.Now > startTime) return 0;
			if (BanQQ.Contains(fromQQ.ToString())) return 0;
			if (!CanUse) return 0;
			if (msg.Contains("title=群公告")) return 0;

			try
			{
				if (General.Handle(fromGroup, fromQQ, msg) == 1)
				{
					return 1;
				}
				if (Global.Authorization)
				{
					if (HandleMsg.Authorization.Handle(fromGroup, fromQQ, msg) == 1)
					{
						return 1;
					}
				}
				else if (UnAuthorization.Handle(fromGroup, fromQQ, msg) == 1)
				{
					return 1;
				}
			}
			catch (AggregateException e)
			{
				CurrentDomain_UnhandledException(null, new UnhandledExceptionEventArgs(e.InnerExceptions[0], false));
			}
			catch (Exception e)
			{
				CurrentDomain_UnhandledException(null, new UnhandledExceptionEventArgs(e, false));
			}

			//if (msg == "1")
			//{
			//	Test2().Wait();
			//}

			return _eventGroupMsg(subType, msgId, fromGroup, fromQQ, fromAnonymous, msg, font);
		}

		static async Task Test2()
		{
			var browser = await Puppeteer.LaunchAsync(new LaunchOptions
			{
				Headless = true,
				ExecutablePath = @"F:\酷Q Pro\dev\com.acgdmzy.acg\chrome-win\chrome.exe",
				Args = new string[] { "--proxy-server=192.168.1.101:2802" }
			});
			var page = await browser.NewPageAsync();
			await page.SetRequestInterceptionAsync(true);
			page.Request += Page_Request;
			await page.GoToAsync("https://twitter.com/wuyu_8512", null, new WaitUntilNavigation[] { WaitUntilNavigation.Networkidle0 });
			//await page.GoToAsync("https://twitter.com/wuyu_8512");
			await page.SetViewportAsync(new ViewPortOptions
			{
				Width = 1080,
				Height = 1920
			});
			await page.ScreenshotAsync("3.jpg");
			await browser.CloseAsync();
		}

		private async static void Page_Request(object sender, RequestEventArgs e)
		{
			if (e.Request.Url.Contains("pbs.twimg.com"))
				await e.Request.AbortAsync();
			else
				await e.Request.ContinueAsync();
		}

		//Type=21 私聊消息
		public static int PrivateMessage(int subType, int msgId, long fromQQ, string msg, int font)
		{
			if (msg.Equals("重启酷Q", StringComparison.OrdinalIgnoreCase) && Master == fromQQ)
			{
				CQ.SendPrivateMessage(fromQQ, "请稍后，酷Q即将重启");
				Win32Help.IniWriteValue(AppDir + "通用设置.ini", "设置", "重启", "1");
				Process.Start(AppDir + "重启.exe");
			}
			else if (msg.Equals("重启酷Q", StringComparison.OrdinalIgnoreCase) && Master == fromQQ)
			{
				CQ.SendPrivateMessage(fromQQ, "请稍后，酷Q即将重载");
				Win32Help.IniWriteValue(AppDir + "通用设置.ini", "设置", "重启", "1");
				Process.Start(AppDir + "重载.exe");
			}
			else if (Master == fromQQ && msg == "更新插件")
			{
				CQ.SendPrivateMessage(fromQQ, "请稍后，插件即将更新");
				File.WriteAllBytes(AppDomain.CurrentDomain.BaseDirectory + "app\\com.acgdmzy.acg.cpk", HttpNet.Get(ServerAddressFile + "com.acgdmzy.acg.cpk"));
				FileInfo fileInfo = new FileInfo(AppDomain.CurrentDomain.BaseDirectory + "app\\com.acgdmzy.acg.cpk");
				if (fileInfo.Length > 716800)
				{
					Win32Help.IniWriteValue(AppDir + "通用设置.ini", "设置", "重启", "1");
					Process.Start(AppDir + "重载.exe");
				}
				else
				{
					CQ.SendPrivateMessage(fromQQ, $"文件大小：{fileInfo.Length / 1024}kb,本次重启取消");
				}
			}
			return CQAPP.消息忽略;
		}

		public static int _menuA()
		{
			if (CanUse)
			{
				new Setting().Show();
			}
			else
			{
				MessageBox.Show("不允许使用插件，可能是未成功初始化或版本太低");
			}
			return 0;
		}

		public static int _menuB()
		{
			return 0;
		}
	}
}
